package org.systm.adminuser.entity;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.experimental.SuperBuilder;
import net.minidev.json.annotate.JsonIgnore;
import org.global.GEntity;
import org.global.basic.JpaArrayPersistence;
import org.global.basic.tree.TreeMeta;
import org.springframework.context.annotation.Lazy;
import javax.persistence.*;
import java.util.List;
import java.util.Objects;

@Getter
@Setter
@SuperBuilder
@AllArgsConstructor
@NoArgsConstructor
@Entity(name = "sys_user_role")
public class UserRole extends GEntity<String> implements TreeMeta {
    @Column(columnDefinition = "varchar(50) not null comment '角色名'")
    private String role;

    @Column(name="`desc`", columnDefinition = "varchar(255) comment '角色描述'")
    private String desc;

    @Column(columnDefinition = "varchar(36) comment '父级'")
    private String pid;

    @Column(columnDefinition = "text comment '菜单'")
    @Convert(converter = JpaArrayPersistence.ListPersistence.class)
    private List<String> menuIds;

    @Lazy
    @ManyToMany
    @JoinTable(
            joinColumns = @JoinColumn(name = "role_id"),
            foreignKey =  @ForeignKey(ConstraintMode.NO_CONSTRAINT),
            inverseJoinColumns = @JoinColumn(name = "per_id"),
            inverseForeignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT)
    )
    private List<UserPermission> permissions;

    @Override
    @Transient
    @JsonIgnore
    public String pid() {
        return this.pid;
    }

    @Override
    @Transient
    @JsonIgnore
    public String id() {
        return super.getId();
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) return false;
        if (this.getClass() == obj.getClass()) return true;
        UserRole userRole = (UserRole) obj;
        return Objects.equals(this.role, userRole.role);
    }

    @Override
    public int hashCode() {
        return Objects.hashCode(role);
    }
}
